package com.kehao.leetcode.jzoffer;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Kehao.Chen
 * @version 1.0
 * @date 2022/6/7 12:31
 */
public class JZSolution002 {
    public String addBinary(String a, String b) {
        int i = a.length()-1,j=b.length()-1;
        char sign = 0;
        List<String> list = new ArrayList<>();
        while (i>=0&&j>=0){
            int result = a.charAt(i) + b.charAt(j) - '0' * 2+sign;
            if(result >= 2){
                sign = 1;
                list.add(String.valueOf(result-2));
            }else {
                sign = 0;
                list.add(result+"");
            }
            i--;
            j--;
        }
        while (i>=0){
            int result = a.charAt(i)  - '0' +sign;
            if(result >= 2){
                sign = 1;
                list.add(String.valueOf(result-2));
            }else {
                sign = 0;
                list.add(result+"");
            }
            i--;
        }

        while (j>=0){
            int result = b.charAt(j)  - '0' +sign;
            if(result >= 2){
                sign = 1;
                list.add(String.valueOf(result-2));
            }else {
                sign = 0;
                list.add(result+"");
            }
            j--;
        }
        if(sign == 1){
            list.add("1");
        }
        Collections.reverse(list);
        return list.stream().reduce((s,c)->s+c).orElse("0");
    }

    @Test
    public void test(){
        String a = "1", b = "111";
        System.out.println(addBinary(a, b));
    }
}
